<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@include file="/pages/basic/html-head.jsp" %>
<div class="container-fluid">
    <div class="body-block-wrapper hidden" id="fromDiv">
        <form id="editForm" method="post">
            <input type="hidden" name="id">
            <input type="hidden" name="voteid">
            <input type="hidden" name="image">
            <input type="hidden" name="descript">
            <div class="form-group">
                <label>名称:</label>
                <input class="easyui-validatebox form-control" type="text" name="title" required/>
                <input type="submit" class="btn btn-myself" value="提交" id="btn-add-save"/>
            </div>
        </form>
    </div>
    <div class="body-block-wrapper">
        <div class="pull-right">
            <div class="input-append">
                <input type="text" placeholder="输入查询关键字" id="fuzzy-search">
                <div class="btn-group">
                    <button type="button" class="btn btn-myself btn-sm" id="btn-search"><i class="fa fa-search"></i>查询
                    </button>
                </div>
            </div>
        </div>
        <button type="button" class="btn btn-myself" id="btn-add"><i class="fa fa-plu"></i> 添加</button>
        <button type="button" class="btn btn-myself" id="btn-del"><i class="fa fa-remove"></i> 删除</button>
        <button type="button" class="btn btn-myself" id="btn-allsceen"><i class="fa fa-upload"></i> 全屏</button>
        <button type="button" class="btn btn-myself" id="btn-return"><i class="fa fa-edit"></i> 返回</button>
    </div>
    <div class="body-block-wrapper">
        <table id="datatable" class="table table-bordered hover " border="1" width="100%">
            <thead>
            <tr>
                <th><input type="checkbox" name="cb-check-all"/></th>
                <th>id</th>
                <th>标题</th>
                <th>数量</th>
                <th>操作</th>
            </tr>
            <thead>
            <tbody></tbody>
        </table>
    </div>
</div>

<script>
    $(function () {
        var $table = $('#datatable');
        var contextPath = '${pageContext.request.contextPath}';
        var _table = $table.dataTable($.extend(true, {}, CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
            ajax: function (data, callback, settings) {//ajax配置为function,手动调用异步查询
                var param = fitParams.getQueryCondition(data);
                $.ajax({
                    type: "POST",
                    url: contextPath + "/votedetail/list",
                    cache: false,  //禁用缓存
                    data: param,    //传入已封装的参数
                    dataType: "json",
                    success: function (result) {
                        //setTimeout仅为测试延迟效果
                        setTimeout(function () {
                            //异常判断与处理
                            if (result.errorCode) {
                                $.messager.alert('提示信息', '查询失败。错误码：' + result.errorCode, 'warning');
                                return;
                            }

                            var returnData = {};
                            returnData.draw = data.draw;
                            returnData.recordsTotal = result.recordsTotal;
                            returnData.recordsFiltered = result.recordsTotal;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.data;

                            //console.debug(data);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }, 200);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('提示信息', '查询失败', 'warning');
                        // $wrapper.spinModal(false);
                    }
                });
            },
            scrollX: "100%",
            columns: [
                CONSTANT.DATA_TABLES.COLUMN.CHECKBOX,
                {
                    className: "ellipsis",
                    data: "id",
                    visible: false
                },
                {
                    className: "ellipsis",
                    data: "title",
                    render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
                    width: "100px"
                },
                {
                    className: "ellipsis",
                    data: "qty",
                    render: CONSTANT.DATA_TABLES.RENDER.ELLIPSIS,
                    width: "100px"
                },
                {
                    className: "td-operation",
                    data: null,
                    defaultContent: "",
                    orderable: false,
                    width: "20px"
                }
            ],
            "createdRow": function (row, data, index) {
                var strHtml = "<div class='btn-group'> " +
                    "<button type='button' class='btn btn-myself btn-edit'><i class='fa fa-edit'></i> 修改</button>" +
                    "</div>";
                var $butoonGroup = $(strHtml);
                $('td', row).eq(3).append($butoonGroup);
            },
            "drawCallback": function (settings) {
                $("tbody tr", $table).eq(0).click();
            }
        })).api();//此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象


        //行点击事件
        $("tbody", $table).on("click", "tr", function (event) {
            //获取该行对应的数据
            var item = _table.row($(this).closest('tr')).data();
            //console.debug(item);
        });

        $table.on("change", ":checkbox", function () {
            if ($(this).is("[name='cb-check-all']")) {
                //全选
                $(":checkbox", $table).prop("checked", $(this).prop("checked"));
            } else {
                //一般复选
                var checkbox = $("tbody :checkbox", $table);
                $(":checkbox[name='cb-check-all']", $table).prop('checked', checkbox.length == checkbox.filter(':checked').length);
            }
        }).on("click", ".td-checkbox", function (event) {
            //点击单元格即点击复选框
            !$(event.target).is(":checkbox") && $(":checkbox", this).trigger("click");
        }).on("click", ".btn-edit", function () {
            //点击编辑按钮
            var item = _table.row($(this).closest('tr')).data();
            $(this).closest('tr').addClass("active").siblings().removeClass("active");
            window.location.href = contextPath + "/votedetail/editview?id=" + item.id;
        });
        //模糊查询事件
        $("#btn-search").click(function () {
            _table.draw();
        });
        ///添加事件
        $("#btn-add").click(function () {
            $('#addForm').form('clear');
            $('#fromDiv').show();
        });
        //添加事件
        $("#btn-allsceen").click(function () {
            $('#addForm').form('clear');
            $('#fromDiv').hide();
        });
        //返回事件
        $("#btn-return").click(function () {
            window.location.href = contextPath + "/vote/main";
        });
        //提交
        $('#editForm').form({
            url: contextPath + "/votedetail/saveorupdate",
            onSubmit: function () {
                return $(this).form('validate');
            },
            success: function (result) {
                if (result.status == "fail") {
                    $.messager.alert("提示信息", "数据添加失败！", "error");
                } else {
                    $.messager.alert("提示信息", "数据添加成功！", "success");
                    //$('#editForm').form('clear');
                }
                _table.draw();
            }
        });
        //$('#editForm').submit();
        //删除事件（支持批量删除）
        $("#btn-del").click(function () {
            var arrItemId = [];
            $("tbody :checkbox:checked", $table).each(function (i) {
                var item = _table.row($(this).closest('tr')).data();
                arrItemId.push(item.id);
            });
            CONSTANT.FUNCTION.deleteItemNoId(arrItemId, contextPath + "/votedetail/delete", _table);
        });
        $("#btn-return-edit").click(function () {
            var voteid = $("#edit-voteid").val();
            window.location.href = contextPath + "/votedetail/main?voteid=" + voteid;
        });

    });


    //组装参数
    var fitParams = {
        currentItem: null,
        getQueryCondition: function (data) {
            var param = {};
            //组装排序参数
            if (data.order && data.order.length && data.order[0]) {
                switch (data.order[0].column) {
                    case 1:
                        param.orderColumn = "id";
                        break;
                    case 2:
                        param.orderColumn = "title";
                        break;
                    case 3:
                        param.orderColumn = "qty";
                        break;
                    default:
                        param.orderColumn = "id";
                        break;
                }
                param.orderDir = data.order[0].dir;
            }
            //组装查询参数
            param.fuzzy = $("#fuzzy-search").val();
            if (param.fuzzy == "") {
                param.fuzzySearch = false;
            } else {
                param.fuzzySearch = true;
            }
            //组装分页参数
            param.currentItem = data.start;
            param.pageSize = data.length;
            param.draw = data.draw;
            return param;
        }

    };


</script>
<%@include file="/pages/basic/html-foot.jsp" %>